/**
 * 
 */
package com.imooc.security.core.social.qq.api;

import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 * 通过token 请求服务提供商的类 API
 *
 * @author zhailiang
 * 多例的
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
	
	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
	
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
	
	private String appId;
	
	private String openId;
	
	private ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * 构造的时候就获取 ，openID，根据 accessToken 去获取
	 * @param accessToken
	 * @param appId
	 */
	public QQImpl(String accessToken, String appId) {
		//把 String accessToken 直接挂到 请求url后面
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
		
		this.appId = appId;
		
		String url = String.format(URL_GET_OPENID, accessToken);
		//发送get请求，请求 url  通过accessToken 获取 openId
		String result = getRestTemplate().getForObject(url, String.class);
		
		System.out.println(result);
		
		this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
	}

	/**
	 * 调用get_user_info接口，获得该用户的头像、昵称并显示在网站上，使用户体验统一。
	 *
	 * https://graph.qq.com/user/get_user_info?	access_token=YOUR_ACCESS_TOKEN	&	oauth_consumer_key=YOUR_APP_ID	&	openid=YOUR_OPENID
	 *
	 * @return
	 */
	@Override
	public QQUserInfo getUserInfo() {
		
		String url = String.format(URL_GET_USERINFO, appId, openId);
		String result = getRestTemplate().getForObject(url, String.class);
		
		System.out.println(result);
		
		QQUserInfo userInfo = null;
		try {
			//	public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean
			userInfo = objectMapper.readValue(result, QQUserInfo.class);
			userInfo.setOpenId(openId);  // 保存openId
			return userInfo;
		} catch (Exception e) {
			throw new RuntimeException("获取用户信息失败", e);
		}
	}

}
